package cn.edu.ctbu.kcsj.service.impl;

import cn.edu.ctbu.kcsj.constain.REnum;
import cn.edu.ctbu.kcsj.domain.Teacher;
import cn.edu.ctbu.kcsj.exception.RException;
import cn.edu.ctbu.kcsj.repository.TeacherRepository;
import cn.edu.ctbu.kcsj.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TeacherImplService implements TeacherService {
    @Autowired
    private TeacherRepository teacherRepository;
    public  List<Teacher> findAll() {
        return teacherRepository.findAll();
    }
    /**
     * 只分页的查询
     * @param pageable
     * @return
     */
    public Page<Teacher> findAll(Pageable pageable){
        return teacherRepository.findAll(pageable);
    }
    /**
     * 分页，带过滤的查询
     * @param teacher
     * @param pageable
     * @return
     */
    public Page<Teacher> findAll(Example<Teacher> teacher, Pageable pageable){
        return teacherRepository.findAll(teacher,pageable);
    }
    public Teacher insert(Teacher teacher){

        return teacherRepository.save(teacher);
    }
    public Teacher update(Teacher teacher){
        return teacherRepository.save(teacher);
    }
    public void delete(Teacher teacher){

        teacherRepository.delete(teacher);
    }
    public void delete(Integer tno){
        Teacher teacher=new Teacher();
        teacher.setTno(tno);
        teacherRepository.delete(teacher);
    }
    public Teacher getByTno(Integer tno){
        Teacher teacher=teacherRepository.findById(tno).orElse(null);
        return teacher;
    }
    @Override
    public Teacher validateTnoAndTpassword(Integer Tno, String password) throws Exception{
        List<Teacher> teachers=teacherRepository.findByTno(Tno);
        if (teachers.size()>0){
            Teacher teacher=teachers.get(0);
            if (teacher.getTpassword().equals(password)){
                return teacher;
            }
            else {
                throw new RException(REnum.LOGIN_ERR);}

        }else {
            throw new RException(REnum.LOGIN_ERR);
        }
    }
    public List<Teacher> findByTnoAndTpassword(Integer tno, String password) {
        return teacherRepository.findByTnoAndTpassword(tno, password);
    }
}
